/**
 * 
 */
package ro.vikingsoft.androidprj;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Comment;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

/**
 * @author voicuad
 * This class is our DAO. 
 * It maintains the database connection and supports adding new tests and fetching all tests.
 */
public class TableTestsDAO {
	// Database fields
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	private String[] allColumns = { MySQLiteHelper.COLUMN_TEST_ID,
			MySQLiteHelper.COLUMN_TEST_TITLE };

	public TableTestsDAO(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public TableTests createTest(String test) {
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_TEST_TITLE, test);
		long insertId = database.insert(MySQLiteHelper.COLUMN_TEST_TITLE, null,	values);
		Cursor cursor = database.query(MySQLiteHelper.COLUMN_TEST_TITLE,
				allColumns, MySQLiteHelper.COLUMN_TEST_ID + " = " + insertId, null,
				null, null, null);
		cursor.moveToFirst();
		TableTests newTest = cursorToTest(cursor);
		cursor.close();
		return newTest;
	}

	public void deleteTest(TableTests test) {
		long id = test.getIdtest();
		
		
		System.out.println("Test deleted with id: " + id);
		database.delete(MySQLiteHelper.TABLE_TESTS, MySQLiteHelper.COLUMN_TEST_ID
				+ " = " + id, null);
	}

	public List<TableTests> getAllTests() {
		List<TableTests> tests = new ArrayList<TableTests>();

		Cursor cursor = database.query(MySQLiteHelper.TABLE_TESTS,
				allColumns, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			TableTests test = cursorToTest(cursor);
			tests.add(test);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return tests;
	}

	private TableTests cursorToTest(Cursor cursor) {
		TableTests test = new TableTests();
		test.setIdtest(cursor.getLong(0));
		test.setTitle(cursor.getString(1));
		return test;
	}
}
